<template>
  <div class="app-container">
    <el-button type="primary" @click="handleAddRole">新增角色</el-button>
    <el-table :data="rolesList" style="width: 100%;margin-top:30px;" border>
      <el-table-column align="center" label="角色代码" width="220">
        <template slot-scope="scope">
          {{ scope.row.roleCode}}
        </template>
      </el-table-column>
      <el-table-column align="center" label="角色名称" width="220">
        <template slot-scope="scope">
          {{ scope.row.roleName}}
        </template>
      </el-table-column>
      <el-table-column align="center" label="角色描述">
        <template slot-scope="scope">
          {{ scope.row.description }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope)">修改角色</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope)">删除角色</el-button>
          <el-button type="primary" size="small" @click="allocateRoutes(scope)">分配路由</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'修改角色':'添加角色'">
      <el-form :model="activeRole" label-width="80px" label-position="left">
        <el-form-item label="角色编码">
          <el-input v-model="activeRole.roleCode" placeholder="角色编码" />
        </el-form-item>
        <el-form-item label="角色名称">
          <el-input v-model="activeRole.roleName" placeholder="角色名称" />
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input
            v-model="activeRole.description"
            type="text"
            placeholder="角色描述"
          />
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmRole">确认</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="treeVisible" width="500px"  :title="treeTitle" class="tree-dialog">
      <el-tree
         ref="tree"
         :data="routesData"
         show-checkbox
         node-key="id"
         :default-checked-keys="checkedKeys"
         class="permission-tree"
        />
        <div style="text-align:right;">
        <el-button type="danger" @click="treeVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmRoutes">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { asyncRoutes } from '@/router/index'
import { getRouteIds, getAllRoles, addRole, deleteRole, updateRole, addRouteIdsForRole} from '@/api/role'

export default {
  data() {
    return {
      routesData: [],
      rolesList: [],
      dialogVisible: false,
      treeVisible: false,
      dialogType: 'new',
      activeRole: '',
      treeTitle: '',
      checkedKeys: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      }
    }
  },
  created() {
    // Mock: get all routes and roles list from server
    this.getRoles()
  },
  methods: {
    getRoutes() {
      this.routesData = this.generateRoutes(asyncRoutes)
    },
    getRoles() {
      getAllRoles().then(res=>{
        if(res.status===200 && res.data.status===200){
            this.rolesList = res.data.data
        }else{
          this.$message({
            message: 'get getAllRoles error:'+res.data.msg,
            type: 'error'
          })
        }
      }).catch(err=>{
          this.$message({
            message: 'get getAllRoles error:'+err,
            type: 'error'
          })
      })
    },

    // Reshape the routes structure so that it looks the same as the sidebar
    generateRoutes(routes) {
      let routeDisplayData = []
      for(let i=0;i<routes.length;i++){
        let routeItem = routes[i]
        let cateItem = {id: parseInt(routeItem.id), label: routeItem.meta && routeItem.meta.title? routeItem.meta.title: routeItem.name, children: []}
        routeDisplayData.push(cateItem)
        if(routeItem.children && routeItem.children.length>0){
            cateItem.children = this.generateRoutes(routeItem.children)
        }
      }
      return routeDisplayData
    },
    handleAddRole() {
      this.dialogType = 'new'
      this.dialogVisible = true
      this.activeRole = {};
    },
    handleEdit(scope) {
      this.dialogType = 'edit'
      this.dialogVisible = true
      this.checkStrictly = true
      this.activeRole = scope.row;
        // this.$refs.tree.setCheckedNodes(this.generateArr(routes))
        // set checked state of a node not affects its father and child nodes
        // this.checkStrictly = false
    },
    handleDelete(scope) {
      this.$confirm('删除角色将一并删除角色用户关系表及角色资源关系表中与该角色关联的记录，是否确定删除?', 'Warning', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const roleId = scope.row.id
          deleteRole(roleId).then(res=>{
            if(res.status===200 && res.data.status===200){
              this.$message({
                type: 'success',
                message: '删除角色成功'
              })
              this.getRoles()
            }else{
              this.$message({
                type: 'error',
                message: '删除角色失败'
              })
            }
          })
        })
        .catch(err => { console.error(err) })
    },
    allocateRoutes(scope) {
       this.treeVisible = true;
       this.activeRole = scope.row
       this.treeTitle = this.activeRole.roleName+'分配路由资源'
       const roleId = scope.row.id;
       if(this.routesData.length===0){
         this.routesData = this.generateRoutes(asyncRoutes)
       }
       this.checkedKeys = []
       getRouteIds(roleId).then(res=>{
         if(res.status===200 && res.data.status===200){
           const chekedRouteIds = res.data.data
           for(let i=0;i<chekedRouteIds.length;i++){
             this.checkedKeys.push(parseInt(chekedRouteIds[i]))
             // 设置角色已有的路由资源
             this.$refs.tree.setCheckedKeys(this.checkedKeys)
           }
         }else{
           this.$message({
            type: 'error',
            message: 'getRouteIds error: ' + res.msg
          })
         }
       })
    },
    
    confirmRole() {
      const isEdit = this.dialogType === 'edit'
      // this.role.routes = this.generateTree(deepClone(this.serviceRoutes), '/', checkedKeys)
      if (isEdit) {
        const role = this.activeRole
        updateRole(role).then(res=>{
          if(res.status===200 && res.data.status===200){
            this.$message({
              type: 'success',
              message: '修改角色成功'
            })
            this.getRoles()
          } else {
             this.$message({
              type: 'error',
              message: '修改角色失败'
            })
          }
        })
        this.dialogVisible = false
      } else {
        const role = this.activeRole
        addRole(role).then(res=>{
           if(res.status===200 && res.data.status===200){
             this.$message({
              type: 'success',
              message: '添加角色成功'
            })
            this.getRoles()
           }else{
              this.$message({
                type: 'error',
                message: '添加角色失败'
              })
           }
        })
        this.dialogVisible = false
      }
    },
    confirmRoutes(){
      const roleId = this.activeRole.id
      const routeIds = this.$refs.tree.getCheckedKeys()
      if(routeIds.length===0){
        this.$message({
          type: 'warning',
          message: '选中的路由ID为空'
        })
        this.treeVisible = false
        return
      }
      addRouteIdsForRole(routeIds, roleId).then(res=>{
        if(res.status===200 && res.data.status===200){
           this.$message({
              type: 'success',
              message: '添加路由资源成功'
            })
        }else{
            this.$message({
                type: 'error',
                message: '添加路由资源失败'
              })
        }
      })
      this.treeVisible = false
    },
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  .roles-table {
    margin-top: 30px;
  }
  .el-dialog_header .el-dialog__title{
    font-size: 20px;
  }
  .tree-dialog {
    margin-left: 200px;
  }
  .permission-tree {
    margin-bottom: 30px;
    height: 320px;
    overflow-y: auto;
  }
}
</style>
